function [summary] = dir_summary(directory, extension)

% dir_summary 10/15/98 P. Manis
% This routine scans a disk for data files and generates a table that summarizes the
% contents of those files, much like headerqw does.
% The results are stored in a structure with the following fields:
%
% table.filename	(string, just the stripped filename)
% table.path		(path string)
% table.filesize	(in records)
% table.comment	(string)
% table.protocols -> protocols is an array structure itself, as follows:
%			protocols(n).proto	the name of the protocol
%			protocols(n).seq		the sequence that was to be run
%			protocols(n).frec		the first record in the protocol
%			protocols(n).lrec		the last record in the protocol
%			protocols(n).ztime	the starting time of the protocol in ztime
%


extension = '*.mat';
if(nargin == 0)

    directory = uigetdir(pwd, 'Data Directory');
    directory
end;
[ofile, opath] = uiputfile('*.txt', 'Output Summary Filename');
ofn = fullfile(opath, ofile);

wmode = 'w';
hchk = fopen(ofn, 'r');
if(hchk > 0) % file exists!
    button = questdlg('Do you want to Overwrite or Replace File?',...
        'Operation','Overwrite','Append','Cancel','Cancel');
    if strcmp(button,'Overwrite')
        arg = 'w';
    elseif strcmp(button,'Append')
        arg = 'a';
    elseif strcmp(button,'Cancel')
        disp('Canceling')
        fclose(hchk)
        return;
    end;
    fclose(hchk);
end;

hout = fopen(ofn, wmode);
if(hout <= 0)
    disp('Failed to open output file');
    return;
end;

summary=[];
[vname, serno] = getdriveinfo(directory);

alldirs = slash4OS([append_backslash(directory), '*']);
whole_dir = dir(alldirs);
selected = [append_backslash(directory), extension];
selected_dir = dir(selected); % the selected files
[path, name, ext, ver] = fileparts(selected); % do this to get the path for reconstructing filename
%selected
n = length(selected_dir);
k = 1; % index into the result table
% first we do the current directory
disp (' Current directory first')
for i=1:n
    if(selected_dir(i).isdir == 0) % only do the real files
        filename=fullfile(path, selected_dir(i).name);
        %      disp(sprintf('Processing: %s', filename))
        [npath, nname, next, nver] = fileparts(filename);
        nname = lower(nname);
        if(any(nname >= 'a' & nname <= 'z'))
            [dfile, data, err] = datac2mat(filename, []);	% just read the header on the file
            if(err==0) % we can load the table
                summary(k).filename = selected_dir(i).name;
                summary(k).path = npath;
                summary(k).filesize = dfile.records_in_file;
                summary(k).comment = dfile.comment;
                if(any(strcmp('Signature', fieldnames(dfile))))
                    summary(k).Signature = dfile.Signature;
                else
                    summary(k).Signature = next; % user extension is "signature"
                end;
                % read the protocol from the note file
                nproto = 0;
                summary(k).protocols = '';
                summary(k).Species = 'unknown';
                summary(k).Weight = 'unknown';
                summary(k).Age = 'unknown';
                summary(k).Sex = 'U';
                if(~strcmp(next, '.mat'))
                    notefile = fullfile(npath, [nname, '.not']);
                else
                    notefile = fullfile(npath, [nname, '.mat']);
                    hdr = load(notefile, 'HFILE'); % read the header to get top information
                    if(isempty(hdr))
                        summary(k).Species = 'unknown';
                        summary(k).Weight = 'unknown';
                        summary(k).Age = 'unknown';
                        summary(k).Sex = 'U';
                    else
                        hdr = hdr.HFILE;
                        summary(k).Species = char(hdr.Species.v);
                        summary(k).Weight = char(hdr.Weight.v);
                        summary(k).Age = char(hdr.Age.v);
                        summary(k).Sex = char(hdr.Sex.v);
                    end;
                    idx = load(notefile, 'Index');
                    wkday = datestr(idx.Index(1).date, 8);
                    tstart = datestr(idx.Index(1).time, 15);
                    tend = datestr(idx.Index(end).time, 15);
                end;
                [proto, err] = note_read(notefile);
                % disp(sprintf('notefile: %s err %d', notefile, err))
                if (err==0)
                    for pi = 1:length(proto)
                        if(pi == 1)
                            summary(k).protocols = proto(pi).proto;
                        else
                            summary(k).protocols = sprintf('%s, %s', summary(k).protocols, proto(pi).proto);
                        end;

                    end;

                end;
                fprintf(1, 'file: %s  ', summary(k).filename);
                fprintf(1, ' %s     %s to %s   %s\n', wkday, tstart, tend, summary(k).Age);

                if(~isempty(summary(k).protocols))
                    fprintf(hout,'%s\t%-15s\t%s\t%s\t%s\t%5d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n', ...
                        local_make_sequence(summary(k).filename), ...
                        summary(k).filename, summary(k).path, vname, serno, summary(k).filesize, ...
                        summary(k).Species, summary(k).Weight, summary(k).Age, summary(k).Sex, ...
                        char(summary(k).Signature), summary(k).comment, summary(k).protocols);
                else
                    fprintf(hout,'%s\t%-15s\t%s\t%s\t%s\t%5d\t%s\t%s\t%s\t%s\t%s\t%s\t<none>\n', ...
                        local_make_sequence(summary(k).filename), ...
                        summary(k).filename, summary(k).path, vname, serno, summary(k).filesize, ...
                        summary(k).Species, summary(k).Weight, summary(k).Age, summary(k).Sex, ...
                        char(summary(k).Signature), summary(k).comment);
                end;


                k = k+1;
            end
        end;
    else
    end
end
% now check for subdirectories off that directory, and do them - allowing ONE level of recursion
m = length(whole_dir);
for j=1:m
    fsprintf(1, '--------Directory #%d: %s \n', j, whole_dir(j).name);
    if(strcmp(whole_dir(j).name, '.')) whole_dir(j).isdir = 0;
    end
    if(strcmp(whole_dir(j).name, '..')) whole_dir(j).isdir = 0;
    end
    if(whole_dir(j).isdir == 1) % only access directories
        cpath = fullfile(path, whole_dir(j).name, extension);	% go to the new directory
        %      disp(sprintf('Doing Subdirectory %s', cpath))
        selected_dir = dir(cpath); % get the file list of what's in the current directory using the base name
        %[cpath, name, ext, ver] = fileparts(nextdir); % do this to get the path for reconstructing filename
        n2 = length(selected_dir); % number of files to process
        % process the files
        for i=1:n2
            if(selected_dir(i).isdir == 0) % only do the real files
                % disp 'a'
                [rpath, filetmp, ext, ver] = fileparts(cpath);
                filename=fullfile(rpath, selected_dir(i).name);
                %            disp(sprintf('Processing: %s', filename))
                [npath, nname, next, nver] = fileparts(filename);
                nname = lower(nname);
                if(any(nname >= 'a' & nname <= 'z'))
                   % disp 'b'
                    [dfile, data, err] = datac2mat(filename, []);	% just read the header on the file
                    if(err==0) % we can load the table
                        summary(k).filename = selected_dir(i).name;
                        summary(k).path = npath;
                        summary(k).filesize = dfile.records_in_file;
                        summary(k).comment = dfile.comment;
                        if(any(strcmp('Signature', fieldnames(dfile))))
                            summary(k).Signature = dfile.Signature;
                        else
                            summary(k).Signature = next; % user extension is "signature"
                        end;
                        % read the protocol from the note file
                        nproto = 0;
                        summary(k).protocols = [];
                        summary(k).Species = 'unknown';
                        summary(k).Weight = 'unknown';
                        summary(k).Age = 'unknown';
                        summary(k).Sex = 'U';
                        if(~strcmp(next, '.mat'))
                            notefile = fullfile(npath, [nname, '.not']);
                        else
                            notefile = fullfile(npath, [nname, '.mat']);
                            hdr = load(notefile, 'HFILE'); % read the header to get top information
                            if(isempty(hdr))
                                summary(k).Species = 'unknown';
                                summary(k).Weight = 'unknown';
                                summary(k).Age = 'unknown';
                                summary(k).Sex = 'U';
                            else
                                hdr = hdr.HFILE;
                                summary(k).Species = char(hdr.Species.v);
                                summary(k).Weight = char(hdr.Weight.v);
                                summary(k).Age = char(hdr.Age.v);
                                summary(k).Sex = char(hdr.Sex.v);
                            end;
                            idx = load(notefile, 'Index');
                            wkday = datestr(idx.Index(1).date, 1);
                            tstart = datestr(idx.Index(1).time, 15);
                            tend = datestr(idx.Index(end).time, 15);
                        end;
                        [proto, err] = note_read(notefile);
                        % disp(sprintf('notefile: %s err %d', notefile, err))
                        if (err==0)
                            for pi = 1:length(proto)
                                if(pi == 1)
                                    summary(k).protocols = proto(pi).proto;
                                else
                                    summary(k).protocols = sprintf('%s, %s', summary(k).protocols, proto(pi).proto);
                                end;

                            end;

                        end;
                        fprintf(1, 'file: %s   ', summary(k).filename);
                        fprintf(1, ' %s     %s to %s   %s\n', wkday, tstart, tend, summary(k).Age);
                        if(~isempty(summary(k).protocols))
                            fprintf(hout,'%s\t%-15s\t%s\t%s\t%s\t%5d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n', ...
                                local_make_sequence(summary(k).filename), ...
                                summary(k).filename, summary(k).path, vname, serno, summary(k).filesize, ...
                                summary(k).Species, summary(k).Weight, summary(k).Age, summary(k).Sex, ...
                                char(summary(k).Signature), summary(k).comment, summary(k).protocols);
                            %     fprintf(1,'%s\t%-15s\t%s\t%s\t%s\t%5d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n', ...
                            %        local_make_sequence(summary(k).filename), ...
                            %        summary(k).filename, summary(k).path, vname, serno, summary(k).filesize, ...
                            %        summary(k).Species, summary(k).Weight, summary(k).Age, summary(k).Sex, ...
                            %        char(summary(k).Signature), summary(k).comment, summary(k).protocols);
                        else
                            fprintf(hout,'%s\t%-15s\t%s\t%s\t%s\t%5d\t%s\t%s\t%s\t%s\t%s\t%s\t<none>\n', ...
                                local_make_sequence(summary(k).filename), ...
                                summary(k).filename, summary(k).path, vname, serno, summary(k).filesize, ...
                                summary(k).Species, summary(k).Weight, summary(k).Age, summary(k).Sex, ...
                                char(summary(k).Signature), summary(k).comment);
                        end;
                        k = k+1;
                    end
                end
            end
        end;
    end
end
fclose(hout);
if(k == 1)
    fprintf(1, sprintf('No files found matching %s\n', extension));
    return
end;


function [seq] = local_make_sequence(file, frec)
% make_sequence  - turn the filename/frec into a number for sorting
% that looks like this:
% yrmdacccc
% where yr is the file year (2 digits), mo is the file month (2 digits), da is the file day (2 digits)
% cc is the file number in the day's experiment (a = 001, etc.), using 3 digits (just in case...)
% and frec is a 4 digit record number entry indicating the first record of the file
%
da=file(1:2);
mon=file(3:5);
yr=file(6:7);
ltr = double(upper(file(8)))-double('A')+1;
month=strvcat('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
monum=strmatch(lower(mon), month, 'exact');
seq = sprintf('%02s%02d%02s%04d', yr, monum, da, ltr);
if(nargin >= 2)
    seq=strcat(seq, sprintf('.%04d', number_arg(frec)));
end;
return

function [vname, serno] = getdriveinfo(directory)

switch(computer())
    case 'PC'

        a = evalc(['!ls ' alldirs]); % to get the volume and serial number of the disk.
        av = findstr('Volume', a); % where are the "volume" words?
        if(length(av) == 1)
            av(2) = 'N';
        end;
        ais = findstr(' is ', a);
        if(isempty(ais))
            ais = findstr(' has ', a); % ?no label
        end;
        if(length(ais) == 1)
            ais(2) = '0';
        end;
        adir = findstr(' Directory ', a);
        if(isempty(ais))
            ais = 'NN';
        end;
        if(isempty(av))
            av = '00';
        end;
        vname = a(ais(1)+4:av(2)-3);
        serno = a(ais(2)+4:adir(1)-2);
        isn=find(serno < 32);
        if(~isempty(isn))
            serno = serno(1:min(isn)-1); % truncate serial number to printable characters
        end;

    case {'MAC', 'MACI'}
        vname = 'HFS formatted volume';
        serno = '0';
    otherwise
end;
